package com.qf.util;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author wgy
 * @version V1.0
 * @project java2402_xiaomi
 * @package com.qf.util
 * @company 千锋教育
 * @date 2024/6/11 10:05
 */
public class DataSourceUtils {
    //创建数据源(连接池)
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
    static {
        try {
            Properties properties=new Properties();
            ClassLoader classLoader = DataSourceUtils.class.getClassLoader();
            InputStream is = classLoader.getResourceAsStream("druid.properties");
            properties.load(is);
            is.close();
            dataSource=new DruidDataSource();
            dataSource.configFromPropety(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static DataSource getDataSource(){
        return dataSource;
    }

    public static Connection getConnection(){
        Connection conn = threadLocal.get();
        try {
            if(conn==null){
                conn= dataSource.getConnection();
                threadLocal.set(conn);
            }
        } catch (SQLException e) {
           e.printStackTrace();
        }
        return conn;
    }
    //事务有关的方法
    //开启事务
    public static void begin() throws SQLException{
        Connection conn = getConnection();
        if (conn != null) {
            conn.setAutoCommit(false);
        }
    }
    public static void commit(){
        try {
            Connection conn = getConnection();
            if (conn != null) {
                conn.commit();
                close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback(){
        try {
            Connection conn = getConnection();
            if (conn != null) {
                conn.rollback();
                close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close(){
        try {
            Connection conn = getConnection();
            if (conn != null) {
                conn.close();
                threadLocal.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
